package com.sky.service.impl;

import ch.qos.logback.classic.spi.LoggerContextAware;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sky.entity.OrderDetail;
import com.sky.entity.Orders;
import com.sky.entity.User;
import com.sky.mapper.OrderDetailMapper;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.vo.OrderReportVO;
import com.sky.vo.SalesTop10ReportVO;
import com.sky.vo.TurnoverReportVO;
import com.sky.vo.UserReportVO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.StringReader;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author
 * @Date 2024/5/19 21:06
 * @Description:
 */
@Service
public class ReportServiceImpl implements ReportService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private UserMapper  userMapper;
    @Override
    public TurnoverReportVO turnoverStatistics(LocalDate beginTime, LocalDate endTime) {
        //将日期存到集合再进行字符串转换
        List<LocalDate> dateList=new ArrayList<>();
        List<Integer>turnoverList=new ArrayList<>();
        dateList.add(beginTime);
        while (beginTime.isBefore(endTime)){
            beginTime=beginTime.plusDays(1);
            dateList.add(beginTime);
        }
        //获取每日最大，最小时间,进行每日销售额统计
        dateList.forEach(date->{
            LocalDateTime begin=LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime end=LocalDateTime.of(date, LocalTime.MAX);
            turnoverList.add((orderMapper.TurnReport(begin,end)));
                });
        return TurnoverReportVO.builder()
                .dateList(StringUtils.join(dateList,","))
                .turnoverList(StringUtils.join(turnoverList,","))
                .build();
    }

    @Override
    public SalesTop10ReportVO top(LocalDate begin, LocalDate end) {
        //拼接好查询时间
        LocalDateTime beginTime=LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime=LocalDateTime.of(end, LocalTime.MAX);
        //查询出时间内所有有效订单
        QueryWrapper <Orders> wrapper=new QueryWrapper<>();
        List<Orders> ordersList = orderMapper.selectList(wrapper.between("order_time", beginTime, endTime).eq("status", 5));
        //收集ordersList内所有的订单id
        List<Long> orderIdList=ordersList.stream().map(Orders::getId).collect(Collectors.toList());
        //查询出所有订单的订单明细
        List<OrderDetail> orderDetails = orderDetailMapper.selectList(new LambdaQueryWrapper<OrderDetail>()
                .in(OrderDetail::getOrderId, orderIdList));
        //收集订单明细的菜品名称
        Set<String> dishNameSet = orderDetails.stream()
                .map(OrderDetail::getName)
                .collect(Collectors.toSet());
//        List<Long> count=new ArrayList<>();
//
//        dishNameSet.forEach(dishName->{
//            count.add(orderDetails.stream().filter(orderDetail -> dishName.equals(orderDetail.getName())).count());
//        });
        Map<String, Long> dishCountMap = orderDetails.stream()
                .collect(Collectors.groupingBy(OrderDetail::getName, Collectors.counting()));

        List<Long> numberList = new ArrayList<>(dishCountMap.values()); // 对应的销售数量列表

        return SalesTop10ReportVO.builder()
                .nameList(StringUtils.join(dishNameSet, ","))
                .numberList(StringUtils.join(numberList, ","))
                .build();
    }

    @Override
    public OrderReportVO orderReportStatistics(LocalDate begin, LocalDate end) {
        LocalDateTime beginTime=LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime=LocalDateTime.of(end, LocalTime.MAX);
        //查询出时间内所有订单
        QueryWrapper <Orders> wrapper=new QueryWrapper<>();
        List<Orders> ordersList = orderMapper.selectList(wrapper.between("order_time", beginTime, endTime));
        //统计每日订单数
        Map<LocalDate, Long> dailyOrderCounts = ordersList.stream()
                .collect(Collectors.groupingBy(order -> order.getOrderTime().toLocalDate(), Collectors.counting()));
        //统计每日有效订单
        Map<LocalDate, Long> dailyValidOrderCounts = ordersList.stream()
                .filter(order -> order.getStatus() == 5)
                .collect(Collectors.groupingBy(order -> order.getOrderTime().toLocalDate(), Collectors.counting()));
        //统计订单总数和有效订单数
        Integer totalOrderCount = Math.toIntExact(dailyOrderCounts.values().stream().mapToLong(Long::longValue).sum());
        Integer totalValidOrderCount = Math.toIntExact(dailyValidOrderCounts.values().stream().mapToLong(Long::longValue).sum());

        //计算订单完成率
        double orderCompletionRate = totalValidOrderCount == 0 ? 0 : (double) totalValidOrderCount / totalOrderCount;

        return OrderReportVO.builder()
                .dateList(StringUtils.join(dailyOrderCounts.keySet(), ","))
                .orderCountList(StringUtils.join(dailyOrderCounts.values(), ","))
                .validOrderCountList(StringUtils.join(dailyValidOrderCounts.values(), ","))
                .totalOrderCount(totalOrderCount)
                .validOrderCount(totalValidOrderCount)
                .orderCompletionRate(orderCompletionRate)
                .build();
    }

    @Override
    public UserReportVO userReportStatistics(LocalDate begin, LocalDate end) {
        LocalDateTime beginTime=LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime=LocalDateTime.of(end, LocalTime.MAX);
        //查询在时间内的新增用户
        QueryWrapper <User> wrapper=new QueryWrapper<>();
        List<User> users = userMapper.selectList(wrapper.between("create_time", beginTime, endTime));

        //统计每日新增用户数
        Map<LocalDate, Long> dailyNewUserCounts = users.stream().collect(Collectors.groupingBy(
              user ->user.getCreateTime().toLocalDate(),Collectors.counting()));
        //统计每日用户总数数、通过当天和前一天用户总数相加获得当天用户总数
        long previousDayCount = 0;

        // 使用一个List来收集每日的累计用户总数
        List<Long> cumulativeUserCounts = new ArrayList<>();

        // 遍历每日新增用户数的条目
        for (Long dailyCount : dailyNewUserCounts.values()) {
            // 当天的用户总数是前一天的总数加上当天新增的数量
            long currentDayCount = previousDayCount + dailyCount;
            // 将当前天的累计用户总数添加到列表中
            cumulativeUserCounts.add(currentDayCount);
            // 更新前一天用户总数为当前天的用户总数，用于下一次迭代
            previousDayCount = currentDayCount;
        }
        return UserReportVO.builder()
                .dateList(StringUtils.join(dailyNewUserCounts.keySet(), ","))
                .totalUserList(StringUtils.join(cumulativeUserCounts, ","))
                .newUserList(StringUtils.join(dailyNewUserCounts.values(), ","))
                .build();
    }
}
